import { RouteRecordWithMenuItem } from "@/router/types";

/**
 * 基于 asyncRoutes 生成左侧菜单的数据
 */
export function genMenuItems(routes: RouteRecordWithMenuItem[]) {
  return routes
    .filter((route) => !route.index)
    .sort((a, b) => {
      return (b.sort || 0) - (a.sort || 0);
    })
    .map((route) => {
      const curRoute = { ...route };
      if (curRoute.children && curRoute.children.length > 0) {
        curRoute.children = genMenuItems(curRoute.children);
      }
      if (curRoute.children && curRoute.children.length === 0) {
        delete curRoute.children;
      }
      return curRoute;
    });
}

/**
 * /dashboard/monitor => ["/dashboard", "/dashboard/monitor"]
 * @param str
 */
export function genMenuOpenKeys(str: string) {
  const arr = str.split("/").filter((item) => item);
  // console.log(arr); // ['dashboard', 'monitor']
  const newArr = arr.reduce(
    (previousValue: string[], currentValue: string, currentIndex: number) => {
      if (currentIndex === 0) {
        previousValue.push(`/${currentValue}`);
      } else {
        previousValue.push(
          `${previousValue[currentIndex - 1]}/${currentValue}`
        );
      }
      return previousValue;
    },
    []
  );
  return newArr;
}

/**
 * 生成一份面包屑key:value的映射
 * const breadcrumbNameMap: Record<string, string> = {
 *   '/apps': 'Application List',
 *   '/apps/1': 'Application1',
 *   '/apps/2': 'Application2',
 *   '/apps/1/detail': 'Detail',
 *   '/apps/2/detail': 'Detail',
 * };
 */
export function genBreadcrumbNameMap(
  menus: RouteRecordWithMenuItem[],
  result: Record<string, string>
) {
  menus.forEach((menu) => {
    if (menu.children && menu.children.length > 0) {
      genBreadcrumbNameMap(menu.children, result);
    }

    result[menu.key] = menu.label;
  });

  return result;
}

/**
 * 获取当前用户有权限的左侧菜单数据
 * [
 *  {
 *    path: '',
 *    key: "/dashboard",
 *    children: [
 *      {
 *        path: '',
 *        key: "/dashboard/analysis"
 *      }
 *    ]
 *  },
 *  {
 *    path: '',
 *    key: '/z'
 *  }
 * ]
 *
 * ["/dashboard/analysis"]  => ["/dashboard", "/dashboard/analysis"]
 */
export function getPermissionMenuItems(
  menuItems: RouteRecordWithMenuItem[],
  permissions: string[]
) {
  // 定义一个结果
  const result: RouteRecordWithMenuItem[] = [];

  menuItems.forEach((item) => {
    if (permissions.includes(item.key)) {
      result.push({ ...item });
    }
  });

  // 判断children
  result.forEach((item) => {
    if (item.children) {
      item.children = getPermissionMenuItems(item.children, permissions);
    }
  });

  return result;
}

/**
 * 检查某个 pathname 是否存在于 menuItems 中
 * @param menuItems
 * @param pathname
 */
export function checkPermission(
  menuItems: RouteRecordWithMenuItem[],
  pathname: string
): boolean {
  return menuItems.some((item) => {
    if (item.key === pathname) {
      return true;
    } else if (item.children) {
      return checkPermission(item.children, pathname);
    } else {
      return false;
    }
  });
}
